package com.samxcode.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C
 * where the candidate numbers sums to T.
 * 
 * The same repeated number may be chosen from C unlimited number of times.
 * 
 * Note: All numbers (including target) will be positive integers. Elements in a combination (a1,
 * a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). The solution set must not
 * contain duplicate combinations. For example, given candidate set 2,3,6,7 and target 7, A solution
 * set is: [7] [2, 2, 3]
 * 
 * NP problem Solutions:
 * backtracking, recursion
 * 1.用当前target减去candidates中的一个作为新的target，将其带入下一次递归；
 * 如果当前target等于0，将结果加入到结果集
 * 2.循环步骤1
 * 
 * 注意在实现中for循环中第一步有一个判断，那个是为了去除重复元素产生重复结果的影响，
 * 因为在这里每个数可以重复使用，所以重复的元素也就没有作用了，所以应该跳过那层递归。
 * 
 * @author Sam
 *
 */
public class CombinationSum {

    public static void main(String[] args) {
        int[] candidates = { 1, 2, 3, 4 };
        System.out.println(combinationSum(candidates, 15));
        
    }


    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (candidates == null || candidates.length == 0) {
            return res;
        }
        Arrays.sort(candidates);
        helper(res, candidates, target, 0, new ArrayList<Integer>());
        return res;
    }


    public static void helper(List<List<Integer>> res, int[] candidates, int target, int start,
            List<Integer> path) {
        if (target == 0) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = start; i < candidates.length && candidates[i] <= target; i++) {
            //skip the repeat
            if (i == 0 || candidates[i] != candidates[i - 1]) {
                path.add(candidates[i]);
                //recursion
                helper(res, candidates, target - candidates[i], i, path);
                //backtracking, delete the add candidate
                path.remove(path.size() - 1);
            }
        }
    }
}
